#include "ttexteditdelegate.h"
#include <QTableWidgetItem>
#include <QTextEdit>

tTextEditDelegate::tTextEditDelegate()
{

}

QWidget *tTextEditDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QTextEdit *editor = new QTextEdit(parent);
    // qDebug()<<index.row()<<index<<1;
    editor->setAcceptRichText(false); // 设置为true则支持富文本，可以显示html标签等，这里设置为false表示不处理富文本
    return editor;
}

void tTextEditDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QString text = index.model()->data(index, Qt::DisplayRole).toString();
    QTextEdit *textEdit = static_cast<QTextEdit*>(editor);
    textEdit->setPlainText(text);
    // qDebug()<<index.row()<<2;
}

void tTextEditDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QTextEdit *textEdit = static_cast<QTextEdit*>(editor);
    QString text = textEdit->toPlainText();
    text.replace("\n","\r\n");
    model->setData(index, text, Qt::EditRole);
    // qDebug()<<index.row()<<3;
}

void tTextEditDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    editor->setGeometry(option.rect);
    // qDebug()<<index.row()<<4;
}

void tTextEditDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QColor alternateColor;
    if (index.row() % 2 == 1) {
        // 设置交替行的背景色
        alternateColor = option.palette.color(QPalette::Base);
    }
    else
    {
        alternateColor = option.palette.color(QPalette::AlternateBase);
    }
    // btnStyle->state |= index.data(Qt::UserRole).toBool() ? QStyle::State_Sunken : QStyle::State_Raised; //设置按钮状态
    if(index.data(Qt::UserRole+1).toBool())
    {
        alternateColor = Qt::red;
    }
    // qDebug()<<"alternateColor"<<alternateColor.name();
    painter->fillRect(option.rect, alternateColor);
    QStyledItemDelegate::paint(painter, option, index);
}

